﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;

namespace Meraz.Web.Models
{
    public class RolesAuthorizeAttribute : AuthorizeAttribute
    {
        public new UserRoles Roles;
        private bool IsAuthorized = false;
        private bool IsAuthenticated = false;

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            if (httpContext.User.Identity.IsAuthenticated)
            {
                IsAuthenticated = true;
                string[] userRoles = System.Web.Security.Roles.GetRolesForUser();
                foreach (string userRole in userRoles)
                {
                    UserRoles role = (UserRoles)Enum.Parse(typeof(UserRoles), userRole);
                    if (Roles.HasFlag(role))
                    {
                        IsAuthorized = true;
                        return true;
                    }
                }
            }
            return false;
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //To allow page level error handling to continue, we can't use the normal
            //status codes, so we're making up some for Unauthorized and Forbidden 
            //when responding to json
            var response = filterContext.HttpContext.Response;
            bool isJson = filterContext.HttpContext.Request.AcceptTypes.Contains("application/json");
            AuthorizeCore(filterContext.HttpContext);
            //base.OnAuthorization(filterContext);
            if (!IsAuthenticated)
            {
                response.StatusCode = (isJson)? 601 : (int) HttpStatusCode.Unauthorized;
                response.AddHeader("MerazHeader", "Only authenticated users permitted.");
                response.Write("Only authenticated users permitted.");
                response.End();
                return;
            }

            if (!IsAuthorized)
            {
                response.StatusCode = (isJson) ? 603 : (int)HttpStatusCode.Forbidden;
                response.AddHeader("MerazHeader", "Only authorized roles permitted.");
                if (isJson)
                {
                    response.Write("Only authorized roles permitted.");
                    response.End();
                }
                else
                    response.Redirect("/Home/NotAuth", true);
            }
        }
    }
}